package com.sanploy.manage.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sanploy.common.conf.PubliceVariable;
import com.sanploy.common.domain.Goods;
import com.sanploy.common.domain.dto.ReduceStockDto;
import com.sanploy.common.domain.dto.StockEditParamDto;
import com.sanploy.common.domain.vo.*;
import com.sanploy.common.enums.Meta;
import com.sanploy.common.util.CommonUtil;
import com.sanploy.common.vo.BaseException;
import com.sanploy.common.vo.FileVo;
import com.sanploy.manage.mapper.GoodsMapper;
import com.sanploy.manage.service.GoodsAttrService;
import com.sanploy.manage.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by zhu yingzhi on 2017/9/6.
 * @author yingzhi zhu
 * 后台商品接口逻辑处理实现类
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsAttrService goodsAttrService;

    private Gson gson = new Gson();

    //更新商品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateGoods(Goods goods, String goodsAttrs_json) throws Exception {
        if (goodsMapper.updateGoods(goods)< PubliceVariable.MinEffectRow){
            throw new BaseException(Meta.UpdateFail);
        }
        goodsAttrService.updateGoodsAttr(goodsAttrs_json,goods.getId());
        return PubliceVariable.SuccessfulInt;
    }

    @Override
    public GoodsDetailVo getGoodsById(Long id) throws BaseException {
        GoodsDetailVo goodsDetailVo = goodsMapper.getGoodsById(id);
        goodsDetailVo.setGoodsAttr_json(gson.toJson(goodsAttrService.findGoodsAttrByGoodsId(id)));
        return goodsDetailVo;
    }

    @Override
    public List<Goods> getGoodsByIdList(List<Long> idList) throws BaseException {
        return goodsMapper.getGoodsByIdList(idList);
    }


    //删除商品
    @Override
    public int deleteGoods(Long id) throws BaseException {
        if (goodsMapper.deleteGoods(id)<PubliceVariable.MinEffectRow){
            throw new BaseException(Meta.DeleteFail);
        }
        return PubliceVariable.SuccessfulInt;
    }

    //添加商品
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int insertGoods(Goods goods,
                           String goodsAttrs_json) throws Exception {
        PicVoUtil(goods);
        if (goods.getGoods_name().contains(",")){
            throw new BaseException(Meta.InsertFail);
        }
        goods.setAdd_time(CommonUtil.getTimeNormal());
        goods.setLast_update(CommonUtil.getTimeNormal());
        if (goodsMapper.insertGoods(goods)< PubliceVariable.MinEffectRow){
            throw new BaseException(Meta.InsertFail);
        }
        goodsAttrService.insertGoodsAttr(goodsAttrs_json,goods.getId());
        return PubliceVariable.SuccessfulInt;
    }

    //后台分页获取商品
    @Override
    public Page<GoodsListVo> getGoodsPage(int currentPage, int pageSize, GoodsSort goodsSort) {
        Page<GoodsListVo> page = new Page<>();
        int total = goodsMapper.getGoodsPageCount(goodsSort); //查找总数并设置返回的页数，及当前的分页信息
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        page.setTotal(total);
        page.setTotalPage((int)Math.ceil((double)total/(double)pageSize));
        page.setList(goodsMapper.getGoodsPage((currentPage-1)*pageSize,pageSize,goodsSort));

        return page;
    }

    //更新促销商品
    @Override
    public int updatePromoteVo(PromoteVo promoteVo) throws BaseException {
        if (goodsMapper.updatePromote(promoteVo)<PubliceVariable.MinEffectRow){
            throw  new BaseException(Meta.UpdateFail);
        }
        return PubliceVariable.SuccessfulInt;
    }

    //获得商品促销信息
    @Override
    public PromoteVo getPromoteVo(Long goods_id) {
        return goodsMapper.getPromote(goods_id);
    }

    //设置商品上下架
    @Override
    public int setShelve(boolean is_shelve,Long goods_id) throws BaseException {
        if (goodsMapper.setShelve(is_shelve, goods_id)<PubliceVariable.MinEffectRow){
            throw  new BaseException(Meta.UpdateFail);
        }
        return PubliceVariable.SuccessfulInt;
    }

    @Override
    public List<SearchResultVo> searchGoodsByName(String name) {
        return goodsMapper.searchGoodsByName(name);
    }

    @Override
    public void reduceGoodsStock(ReduceStockDto reduceStockDto) {
        for (int i = 0; i < reduceStockDto.getGoodsIds().length; i++) {
            goodsMapper.reduceGoodsStock(reduceStockDto.getGoodsNumbers()[i],reduceStockDto.getGoodsIds()[i]);
        }
    }

    @Override
    public void restoreGoodsStock(ReduceStockDto reduceStockDto) {
        for (int i = 0; i < reduceStockDto.getGoodsIds().length; i++) {
            goodsMapper.restoreGoodsStock(reduceStockDto.getGoodsNumbers()[i],reduceStockDto.getGoodsIds()[i]);
        }
    }

    @Override
    public int editGoodsStock(StockEditParamDto stockEditParamDto) {
        for (int i=0;i<stockEditParamDto.getStock().length;i++){
            goodsMapper.editGoodsStock(stockEditParamDto.getStock()[i], stockEditParamDto.getGoodsId()[i]);
        }
        return PubliceVariable.SuccessfulInt;
//        return goodsMapper.editGoodsStock(stock, goodsId);
    }


    /**
     * 解析前端上传的商品中图片对象的处理
     * @param goods
     */
    private void PicVoUtil(Goods goods){

        List<FileVo> pic_banner= gson.fromJson(goods.getPic_banner(),new TypeToken<List<FileVo>>(){}.getType());
        List<FileVo> pic_main= gson.fromJson(goods.getPic_main(),new TypeToken<List<FileVo>>(){}.getType());

        StringBuffer pic_banner_str = new StringBuffer();
        StringBuffer pic_main_str = new StringBuffer();
        pic_banner.forEach(fileVo -> {
        pic_banner_str.append(fileVo.getSavePath());
        pic_banner_str.append(",");
        });
        pic_main.forEach(fileVo -> {
            pic_main_str.append(fileVo.getSavePath());
            pic_main_str.append(",");
        });

        if (pic_banner_str.length() > 0){
            goods.setPic_banner(pic_banner_str.substring(0,pic_banner_str.length()-1));
        }

        if (pic_main_str.length() > 0){
            goods.setPic_main(pic_main_str.substring(0,pic_main_str.length()-1));
        }

    }
}
